package com.pet.cart.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.api.client.ItemClient;
import com.pet.api.dto.ItemDTO;
import com.pet.api.dto.OrderDetailDTO;
import com.pet.cart.domain.dto.CartItemDTO;
import com.pet.cart.domain.po.Cart;
import com.pet.cart.domain.vo.CartVO;
import com.pet.cart.mapper.CartMapper;
import com.pet.cart.service.ICartService;
import com.pet.common.domain.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author Cookies
 * @since 2024-07-11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {
    private final ItemClient itemClient;

    @Override
    public boolean addItem2Cart(CartItemDTO cartItemDTO) {
        Integer userId = UserContext.getUser();
        Integer itemId = cartItemDTO.getItemId();
        // 检查购物车是否存在该商品
        if (checkItemExists(itemId, userId)) {
            // 存在则更新数量
            return baseMapper.updateNum(itemId, userId, cartItemDTO.getQuantity());
        }
        ItemDTO itemDTO = itemClient.getItemById(itemId);
        // 保存数据
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setItemId(itemId);
        cart.setNumber(cartItemDTO.getQuantity());
        cart.setPrice(itemDTO.getPrice());
        return save(cart);
    }

    @Override
    public List<CartVO> getCartItemsByUser() {
        Integer userId = UserContext.getUser();
        List<Cart> cartList = lambdaQuery()
                .eq(Cart::getUserId, userId)
                .list();
        if (CollUtil.isEmpty(cartList)) {
            return Collections.emptyList();
        }
        List<CartVO> cartVOList = BeanUtil.copyToList(cartList, CartVO.class);
        // 处理VO中的商品信息
        handleCartItems(cartVOList);
        return cartVOList;
    }

    @Override
    public boolean removeItemsByIds(List<Integer> ids) {
        // 获取用户id
        Integer userId = UserContext.getUser();
        // 删除
        return lambdaUpdate()
                .eq(Cart::getUserId, userId)
                .in(Cart::getItemId, ids)
                .remove();
    }

    @Override
    public void addItemsByIds(List<OrderDetailDTO> detailDTOList) {
        // 获取用户id
        Integer userId = UserContext.getUser();
        // 获取商品列表
        Map<Integer, Integer> itemNumMap = detailDTOList.stream()
                .collect(Collectors.toMap(OrderDetailDTO::getItemId, OrderDetailDTO::getNum));
        Set<Integer> ids = itemNumMap.keySet();
        List<ItemDTO> itemDTOList = itemClient.getItemsByIds(ids);
        // 保存商品快照到购物车
        List<Cart> cartList = new ArrayList<>(itemDTOList.size());
        itemDTOList.stream().forEach(itemDTO -> {
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setItemId(itemDTO.getId());
            cart.setNumber(itemNumMap.get(itemDTO.getId()));
            cart.setPrice(itemDTO.getPrice());
            cartList.add(cart);
        });
        saveBatch(cartList);
    }

    private void handleCartItems(List<CartVO> cartVOList) {
        // 获取商品id
        Set<Integer> itemIds = cartVOList.stream().map(CartVO::getItemId).collect(Collectors.toSet());
        List<ItemDTO> items = itemClient.getItemsByIds(itemIds);
        if (CollUtil.isEmpty(items)) {
            return;
        }
        // 转为id到item的map
        Map<Integer, ItemDTO> itemMap = items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity()));
        // 写入vo
        for (CartVO cartVO : cartVOList) {
            ItemDTO item = itemMap.get(cartVO.getItemId());
            if (item == null) {
                continue;
            }
            cartVO.setName(item.getTitle());
            cartVO.setImage(item.getImage());
            cartVO.setNewPrice(item.getPrice());
        }
    }

    private boolean checkItemExists(Integer itemId, Integer userId) {
        Integer count = lambdaQuery()
                .eq(Cart::getUserId, userId)
                .eq(Cart::getItemId, itemId)
                .count();
        return count > 0;
    }
}
